package sundun.sharding.algorithm;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;
import sundun.sharding.algorithm.CustomComplexShardingAlgorithm;
import sundun.sharding.common.AbstractComplexSharding;
import sundun.sharding.common.complex.ComplexShardingParam;
import sundun.sharding.common.complex.ComplexShardingParamValue;
import sundun.sharding.common.complex.ComplexShardingType;
import sundun.sharding.constant.ShardingConstant;
import sundun.sharding.enums.ShardingTableCacheEnum;
import sundun.sharding.properties.ShardingJdbcProperties;
import sundun.sharding.utils.ShardingAlgorithmUtil;
import sundun.sharding.utils.SpringUtil;
import sundun.sharding.utils.TimeFrameEndpointUtil;

import java.text.ParseException;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 自定义分片策略
 * 先通过时间字段以年份分组，再针对年份下面设置多个节点进行存储
 * 分片格式 表名_年份_节点（ims_yesterday_jqxx_2024_0）
 * （仅支持两个字段分片，取第一个分片字段为范围分片，取第二个字段为取模分片 ）
 * @author zxl
 * @date 2024/07/31 15:03
 */
@Slf4j
public class CustomComplexShardingAlgorithmOne extends CustomComplexShardingAlgorithm {


    @Override
    public Collection<String> doSharding(Collection<String> tableNames, ComplexKeysShardingValue<Comparable<?>> shardingValue) {
        return super.doSharding(tableNames, shardingValue);
    }

    @Override
    protected void deliveryAlgorithm(String singleValue, String tableName, Collection<String> shardingResult, ShardingJdbcProperties shardingJdbcProperties) {
        singleValue = singleValue.replaceAll("[\\[\\]]", ""); // 清除字符串中的"["和"]"
        // 根据分片键值取前六位，可自定义，防止字段过长导致Long类型转换失败
        String substring = singleValue.substring(6);
        int tableIndex = Math.abs(Integer.parseInt(substring) % shardingJdbcProperties.getNodes());
        // 构造表名
        String tableNameNode = tableName + ShardingConstant.TABLE_SPLIT_SYMBOL + tableIndex;
        shardingResult.add(tableNameNode);
    }
}
